//pinia
import {
	useLoadingStore
} from "@/stores/useLoadingStore.js"
const LoadingStore = useLoadingStore()



/**
 * 保存图片到相册（H5跳转，MP下载）
 * @param {String} url 图片远程地址 必填
 */
const downloadImg = (url) => {
	if (!url) return
	// #ifdef H5
	// window.location.href = url
	uni.showToast({
		title: '长按保存图片',
		icon: "none",
		complete: () => {
			setTimeout(()=>{
				// previewModel(url)
				// window.open(url)
				location.href = url;
			},1500)
		}
	})

	// #endif

	// #ifndef H5
	uni.downloadFile({
		url: url,
		success: (resFile) => {
			// 图片下载成功
			if (resFile.statusCode === 200) {
				//获取用户的授权情况
				uni.getSetting({
					success: (res) => {
						// 用户没有授权相册
						if (!res.authSetting["scope.writePhotosAlbum"]) {
							// 申请相册授权
							uni.authorize({
								scope: "scope.writePhotosAlbum",
								success: () => {
									// 用户同意授权，保存图片到相册
									uni.saveImageToPhotosAlbum({
										filePath: resFile
											.tempFilePath,
										success: (res) => {
											return uni
												.showToast({
													title: "保存成功！",
												});
										},
										fail: (res) => {
											return uni
												.showToast({
													title: '保存失败',
												});
										},
										complete: (res) => {},
									});
								},
								fail: () => {
									// 用户拒绝授权，提示用户调整授权
									uni.showModal({
										title: "您已拒绝获取相册权限",
										content: "是否进入权限管理，调整授权？",
										success: (res) => {
											if (res.confirm) {
												uni.openSetting({
													success: (
														res
													) => {
														console
															.log(
																res
																.authSetting
															);
													},
												});
											} else if (res
												.cancel) {
												return uni
													.showToast({
														title: "已取消！",
													});
											}
										},
									});
								},
							});
						} else {
							// 已授权相册
							uni.saveImageToPhotosAlbum({
								filePath: resFile.tempFilePath,
								success: (res) => {
									return uni.showToast({
										title: "保存成功！",
									});
								},
								fail: (res) => {
									return uni.showToast({
										title: res.errMsg,
									});
								},
								complete: (res) => {},
							});
						}
					},
					fail: (res) => {},
				});
			} else {
				return uni.showToast({
					title: resFile.errMsg,
				});
			}
		},
		fail: (res) => {
			return uni.showToast({
				title: '下载文件失败',
			});
		},
		complete: () => {
			LoadingStore.setLoading(false)
		}
	});
	// #endif
}


//预览模型
const previewModel = (urls, current = 0) => {
	if(typeof urls === 'string'){
		urls = [urls]
	}
	uni.previewImage({
		urls: urls,
		current: current,
		complete: () => {
			LoadingStore.setLoading(false)
		}
	});
}

export {
	downloadImg,
	previewModel
}